<template>
	<view class="home-search">
		<navbar :isSearch="true" @change="change"></navbar>
		<view class="home-list">
			<view class="label-box" v-if="isHistotry">
				<view class="label-header">
					<text class="label-title">搜索历史</text>
					<text class="label-clear" @click="clear">清空</text>
				</view>
				<view class="label-content">
					<view class="label-content__item" v-for="(item, index) in  historyList" :key="index">
						{{ item.name }}
					</view>
				</view>
				<view class="no-data">
					没有搜索历史
				</view>
			</view>
			<list-scroll v-else class="list-scroll">
				<list-card :item="item" v-for="(item, index) in searchList" :key="index" @click="setHistory"></list-card>
			</list-scroll>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				isHistotry: false,
				searchList: [],
				mark: '',
				timer: '',
				value: ''
			}
		},
		computed: {
				...mapState(['historyList'])
		},
		onLoad() {
			// this.getSearch('')
		},
		methods: {
			change (value) {
				
				if (!value) {
					clearTimeout(this.timer)
					this.mark = false
					this.getSearch (value)
					return
				}
				
				if (!this.mark) {
					this.mark = true
					this.timer = setTimeout(() => {
						this.mark = false
						this.getSearch(value)
						this.value = value
					},300)
				}
			},
			getSearch (value) {
				if (!value) {
					this.searchList = []
					this.isHistotry = true
					return
				}
				this.isHistotry = false
				this.$api.get_search({
					value
				}).then((res) => {
					// console.log(res)
					const { data } = res
					this.searchList = data
				})
			},
			setHistory () {
				// console.log('---------------')
				this.$store.dispatch('setHistoryList', {
					name: this.value
				})	
			},
			clear () {
				this.$store.dispatch('clearHistryList')
				uni.showToast({
					title:"清空完成"
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		display: flex;
		background-color: #f5f5f5;
		.home-search {
			display: flex;
			flex-direction: column;
			flex: 1;
			.label-box {
				background: #ffffff;
				margin-bottom: 10px;
				.label-header {
					display: flex;
					justify-content: space-between;
					font-size: 14px;
					color: #666;
					padding: 10px 15px;
					border-bottom: 1px #f5f5f5 solid;
					.label-title {
						color: $mk-base-color;
					}
					.label-clear {
						color: #30b33a;
					}
				}
				.label-content {
					display: flex;
					flex-wrap: wrap;
					padding: 15px;
					padding-top: 0;
					.label-content__item {
						padding: 2px 10px;
						margin-top: 12px;
						margin-right: 10px;
						border-radius: 5px;
						border: 1px #666 solid;
						font-size: 14px;
						color: #666;
					}
				}
			}
		}
		.no-data {
			height: 200px;
			line-height: 200px;
			width: 100%;
			text-align: center;
			color: #666;
			font-size: 14px;
		}
	}
</style>
